package sketch.util;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

public class ReflectiveExecutionsTest extends TestCase {
	
	public static Test suite() {
        return new TestSuite(ReflectiveExecutionsTest.class);
    }
	
	public void testMethodExecution() {
		TreeMap map = new TreeMap();
		map.put(1);
		map.put(2);
		Method[] methods = TreeMap.class.getDeclaredMethods();
		for(Method m : methods) {
			if(m.getName().equals("size")) {
				ReflectionExecutionOutcome outcome = ReflectiveExecutions.executeMethod(m, map, new Object[0]);
				System.out.println("The execution result is: " + outcome.reflectionCode.getReturnVariable());
				assertTrue(outcome.reflectionCode.getReturnVariable().equals(2));
				break;
			}
		}
		System.out.println();
		assertTrue(map.size() == 2);
	}
	
	public void testMethodExecution2() {
		TreeMap map = new TreeMap();
		map.put(1);
		map.put(2);
		Method[] methods = TreeMap.class.getDeclaredMethods();
		for(Method m : methods) {
			if(m.getName().equals("put")) {
				ReflectionExecutionOutcome outcome = ReflectiveExecutions.executeMethod(m, map, new Object[]{3});
				System.out.println("The execution result is: " + outcome.reflectionCode.getReturnVariable());
				assertTrue(outcome.reflectionCode.getReturnVariable() == null);
				break;
			}
		}
		System.out.println("After execution, the size of tree map: " + map.size());
		System.out.println();
		assertTrue(map.size() == 3);
	}
	
	public void testConstructorExecution() {
		System.out.println();
		Constructor<?>[] constructors = TreeMap.class.getDeclaredConstructors();
		for(Constructor<?> constructor : constructors) {
			System.out.println("Invoking constructor!");
			ReflectionExecutionOutcome outcome = ReflectiveExecutions.executeConstructor(constructor, new Object[0]);
			assertTrue (outcome.reflectionCode.getReturnVariable() != null);
		}
	}
	
}